package com.shujia.hadoop.mr;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class MR07 {
    public static class JoinMapper extends Mapper<LongWritable,Text,Text,Text>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            InputSplit inputSplit = context.getInputSplit ( );
            FileSplit fileSplit=(FileSplit)inputSplit;
            String path = fileSplit.getPath ( ).toString ( );
            if (path.contains ("students")){
                String id = value.toString ( ).split (",")[0];
                String stu="$"+value.toString ();

                context.write (new Text (id),new Text (stu));
            }else{
                String id = value.toString ( ).split (",")[0];
                String stu="#"+value.toString ();
                context.write (new Text (id),new Text (stu));
            }

        }
    }
    public static class JoinReducer extends Reducer<Text,Text,Text,NullWritable>{
        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            StringBuffer sb = new StringBuffer ( );
            for (Text text : values) {
                sb.append (text.toString ());
            }
            context.write (new Text (sb.toString ()),NullWritable.get ());
        }
    }
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Job job = Job.getInstance ( );
        job.setJobName ("join");
        job.setJarByClass (MR07.class);

        job.setMapOutputKeyClass (Text.class);
        job.setMapOutputValueClass (Text.class);
        job.setReducerClass (JoinReducer.class);
        job.setOutputKeyClass (Text.class);
        job.setOutputValueClass (NullWritable.class);
        Path input = new Path ("/students.txt");
        FileInputFormat.addInputPath (job,input);
        Path input1 = new Path ("/score.txt");
        FileInputFormat.addInputPath (job,input1);
        Path output = new Path ("/output");
        FileSystem fs = FileSystem.get (new Configuration ( ));
        if (fs.exists (output)){
            fs.delete (output,true);
        }
        FileOutputFormat.setOutputPath (job,output);
        job.waitForCompletion (true);

    }
}
